﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Futaba.SBus.Extensions
{
	/// <summary>
	/// Validates the parameters of method calls and throws corresponding <see cref="ArgumentException"/>
	/// inheriting exception-types
	/// </summary>
	public static class ValidationExtensions
	{

		/// <summary>
		/// Ensures that the <paramref name="target"/> is not null
		/// </summary>
		/// <exception cref="ArgumentNullException"></exception>
		public static void EnsureNotNull(this object target, string paramName, string msg = null, params object[] args)
		{
			if (target != null)
				return;
			if (string.IsNullOrEmpty(msg))
				throw new ArgumentNullException(paramName);
			else
			{
				if (args == null || args.Length == 0)
					throw new ArgumentNullException(paramName, msg);
				else
					throw new ArgumentNullException(paramName, string.Format(msg, args));
			}
		}

		/// <summary>
		/// Ensures that the <paramref name="target"/> is not null and not empty
		/// </summary>
		/// <exception cref="ArgumentNullException"></exception>
		/// <exception cref="ArgumentOutOfRangeException"></exception>
		public static void EnsureNotEmpty(this IEnumerable target, string paramName, string msg = null, params object[] args)
		{
			target.EnsureNotNull(paramName, msg, args);
			if (target.Cast<object>().Any())
				return;

			if (string.IsNullOrEmpty(msg))
				throw new ArgumentOutOfRangeException(paramName);
			else
			{
				if (args == null || args.Length == 0)
					throw new ArgumentOutOfRangeException(paramName, msg);
				else
					throw new ArgumentOutOfRangeException(paramName, string.Format(msg, args));
			}
		}

	}
}
